package cn.stylefeng.guns.modular.hx.storage.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.shiro.annotion.Permission;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicOperateService;
import cn.stylefeng.guns.modular.basic.service.BasicPutgoodsService;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageStock;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageStockParam;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageStockService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.util.ToolUtil;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 库存表控制器
 *
 * @author zhucx
 * @Date 2023-08-15 15:56:34
 */
@Controller
@RequestMapping("/hxStorageStock")
public class HxStorageStockController extends BaseController {

    private final String PREFIX = "/hx/storage/hxStorageStock";
    private final String PREFIX1 = "/hx/storage/hxDateStatistics";

    @Autowired
    private HxStorageStockService hxStorageStockService;

    @Autowired
    private UserService userService;

    @Autowired
    private BasicWarehouseService basicWarehouseService;

    @Autowired
    private BasicCustomerService basicCustomerService;
    @Autowired
    private BasicOperateService basicOperateService;
    @Autowired
    private BasicPutgoodsService basicPutgoodsService;



    /**
     * 库存效期统计
     *
     * @author lww
     * @Date 2023-08-15
     */
    @RequestMapping("/hxDateStatistics")
    public String hxdatestatistics(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX1 + "/hxDateStatistics.html";
    }
    /**
     * 跳转到主页面
     *
     * @author zhucx
     * @Date 2023-08-15
     */
    @RequestMapping("")
    public String index(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/hxStorageStock.html";
    }
    
    /**
     * 跳转转仓选择库存页面
     */
    @RequestMapping("tochoiceStorageStock")
    public String tochoiceStorageStock() {
        return PREFIX + "/choiceStorageStock.html";
    }

    /**
     * 新增页面
     *
     * @author zhucx
     * @Date 2023-08-15
     */
    @RequestMapping("/add")
    public String add(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
        //查询可选择项目
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        //查询可选择发货客户
//        model.addAttribute("basicPutgoodsList", basicPutgoodsService.findAvailableList(deptId,deliverId,user.getOperateId()));

        return PREFIX + "/hxStorageStock_add.html";
    }

    /**
     * 编辑页面
     *
     * @author zhucx
     * @Date 2023-08-15
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/hxStorageStock_edit.html";
    }

    /**
     * 选择商品页面
     */
    @RequestMapping("/toChoiceGoods")
    public String toChoiceGoods() {
        return PREFIX + "/choiceGoods.html";
    }
    /**
     * 新增接口
     *
     * @author zhucx
     * @Date 2023-08-15
     */
    @RequestMapping("/addItem")
    @ResponseBody
//    @Permission
    public ResponseData addItem(HxStorageStockParam hxStorageStockParam) {
        User user = userService.getcurrentUser();
        this.hxStorageStockService.addItem(hxStorageStockParam,user);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author zhucx
     * @Date 2023-08-15
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(HxStorageStockParam hxStorageStockParam) {
        this.hxStorageStockService.update(hxStorageStockParam);
        return ResponseData.success();
    }

    /**
     * 清空库存接口
     */
    @RequestMapping("/clearAll")
    @ResponseBody
    @Permission
    public ResponseData clearAll(HxStorageStockParam hxStorageStockParam) {
    	if(ToolUtil.isEmpty(hxStorageStockParam.getWarehouseId())) {
            return ResponseData.error("仓库不得为空");
    	}
    	hxStorageStockService.deleteBySpec(hxStorageStockParam);
        return ResponseData.success();
    }

    /**
     * 批量删除接口
     */
    @RequestMapping("/btnRevoke")
    @ResponseBody
    @Permission
    public ResponseData btnRevoke(Integer[] ids) {
        for (Integer id : ids) {
            HxStorageStockParam param = new HxStorageStockParam();
            param.setId(id);
            this.hxStorageStockService.delete(param);
        }
        return ResponseData.success();
    }
    
    /**
     * 删除接口
     *
     * @author zhucx
     * @Date 2023-08-15
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(HxStorageStockParam hxStorageStockParam) {
        this.hxStorageStockService.delete(hxStorageStockParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author zhucx
     * @Date 2023-08-15
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(HxStorageStockParam hxStorageStockParam) {
        HxStorageStock detail = this.hxStorageStockService.getById(hxStorageStockParam.getId());
        return ResponseData.success(detail);
    }
    /**
     * 查看详情接口
     *
     * @author zhucx
     * @Date 2023-08-15
     */
    @RequestMapping("/details")
    @ResponseBody
    public ResponseData details(HxStorageStockParam hxStorageStockParam) {
        HxStorageStockParam detail = this.hxStorageStockService.details(hxStorageStockParam);
        if (ToolUtil.isNotEmpty(detail)){
            return ResponseData.success(detail);
        }else {
            return ResponseData.error("打印失败，明细和配送单位才可以打印");
        }
    }

    /**
     * 查询列表
     *
     * @author zhucx
     * @Date 2023-08-15
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(HxStorageStockParam hxStorageStockParam, String condition) {
        User user = userService.getcurrentUser();
        hxStorageStockParam.setOperateId(user.getOperateId());
        hxStorageStockParam.setDeptId(user.getDeptId());
        hxStorageStockParam.setDeliverId(user.getDeliverId());
        return this.hxStorageStockService.findPageBySpec(hxStorageStockParam,condition);
    }

    @ResponseBody
    @RequestMapping("/list2")
    public ResponseData list2(HxStorageStockParam hxStorageStockParam, String condition) {
        User user = userService.getcurrentUser();
        hxStorageStockParam.setOperateId(user.getOperateId());
        hxStorageStockParam.setDeptId(user.getDeptId());
        hxStorageStockParam.setDeliverId(user.getDeliverId());
        return this.hxStorageStockService.findPageBySpec2(hxStorageStockParam,condition);
    }

    /**
     * 查询列表
     * @author zhucx
     * @Date 2023-08-15
     */
    @ResponseBody
    @RequestMapping("/listAll")
    public List<HxStorageStockParam> listAll(HxStorageStockParam hxStorageStockParam, String condition) {
        User user = userService.getcurrentUser();
        hxStorageStockParam.setOperateId(user.getOperateId());
        hxStorageStockParam.setDeptId(user.getDeptId());
        hxStorageStockParam.setDeliverId(user.getDeliverId());
        return this.hxStorageStockService.findlistAllBySpec(hxStorageStockParam,condition);
    }


    /**
     * 导出盘点表
     * @param hxStorageStockParam
     * @param condition
     * @param response
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("/exportToExcel")
    public void exportToExcel(HxStorageStockParam hxStorageStockParam, String condition, HttpServletResponse response) throws IOException {
        User user = userService.getcurrentUser();
        hxStorageStockParam.setOperateId(user.getOperateId());
        hxStorageStockParam.setDeptId(user.getDeptId());
        hxStorageStockParam.setDeliverId(user.getDeliverId());
        List<HxStorageStockParam> pdList = this.hxStorageStockService.findlistAllBySpecPd(hxStorageStockParam, condition);

        XSSFWorkbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("盘点信息表");

        // 创建标题行
        Row titleRow = sheet.createRow(0);
        titleRow.createCell(1).setCellValue("库区名称");
        titleRow.createCell(2).setCellValue("库位编号");
        titleRow.createCell(3).setCellValue("商品名称");
        titleRow.createCell(4).setCellValue("商品编码");
        titleRow.createCell(5).setCellValue("初盘");
        titleRow.createCell(6).setCellValue("复盘");
        titleRow.createCell(7).setCellValue("差异");
        titleRow.createCell(8).setCellValue("库存数量");

        // 添加数据行
        for (int i = 0; i < pdList.size(); i++) {
            Row row = sheet.createRow(i + 1);
            HxStorageStockParam param = pdList.get(i);
            row.createCell(1).setCellValue(param.getAreaName() == null ? "" : param.getAreaName());
            row.createCell(2).setCellValue(param.getPositionNumber() == null ? "" : param.getPositionNumber());
            row.createCell(3).setCellValue(param.getGoodsName() == null ? "" : param.getGoodsName());
            row.createCell(4).setCellValue(param.getGoodsNumber() == null ? "" : param.getGoodsNumber());
            row.createCell(8).setCellValue(param.getKcNum() == null ? "" : param.getKcNum());
        }

        // 设置响应头
        OutputStream output = response.getOutputStream();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(("盘点信息" + ".xlsx").getBytes(), "iso-8859-1"));
        // 写入响应
        try (OutputStream excelOutput = output) {
            wb.write(excelOutput);
        }
        wb.close();
    }


    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcel")
    public String toimportExcel(Model model) {
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择分公司
        model.addAttribute("basicOperatelist", basicOperateService.findAvailableList(deptId,deliverId,user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId, deliverId,user.getOperateId()));
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/import.html";
    }

    /**
     * 导入excel
     */
    @RequestMapping(value = "/importExcel" , method = {RequestMethod.POST} )
    @ResponseBody
    @Permission
    public ResponseData importExceNewmethodl(@RequestPart("file") MultipartFile file, HxStorageStockParam hxStorageStockParam)  {
        ResponseData data = new ResponseData();
        User user = userService.getcurrentUser();
        try {
            data = hxStorageStockService.getExceldata(file,hxStorageStockParam,user,data);//处理导入数据
        } catch (Exception e) {
            data.setSuccess(false);
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 下载模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcel")
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException {
        String path = "assets/excel/hxStorageGoods.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("零售库存导入模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 去打印标签页面
     */
    @RequestMapping("/tobtnqrCode")
    public String tobtnqrCode() {
        return PREFIX + "/btnqrCode.html";
    }

    /**
     * 查询列表
     * @author zhucx
     * @Date 2023-08-15
     */
    @ResponseBody
    @RequestMapping("/choicelist")
    public LayuiPageInfo choicelist(HxStorageStockParam hxStorageStockParam, String condition) {
        User user = userService.getcurrentUser();
        hxStorageStockParam.setOperateId(user.getOperateId());
        hxStorageStockParam.setDeptId(user.getDeptId());
        return this.hxStorageStockService.findchoicePageBySpec(hxStorageStockParam,condition);
    }



}
